package br.ufmg.vod.wbr;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.commons.io.EndianUtils;
import org.apache.commons.io.LineIterator;

import com.sun.xml.internal.messaging.saaj.packaging.mime.util.LineInputStream;


public class IOUtil {
	
	public static int countLines(File file) throws IOException{
		int lc = 0;
		BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
		while( in.readLine()!=null) {
			lc++;
		}
		return lc;
	}

	
	public static long readUnsignedInt(RandomAccessFile input) throws IOException {
		return (input.read() & 0xFFl) | (input.read() & 0xFFl) << 8l | (input.read() & 0xFFl) << 16l | (input.read() & 0xFFl) << 24l;
	}
	
	public static int readUnsignedShort(RandomAccessFile input) throws IOException {
		return (input.read() & 0xFF) | (input.read() & 0xFF) << 8;
	}
	
	
	
	public static long readUnsignedInt(InputStream input) throws IOException {
		return (input.read() & 0xFFl) | (input.read() & 0xFFl) << 8l | (input.read() & 0xFFl) << 16l | (input.read() & 0xFFl) << 24l;
	}
	
	public static int readUnsignedShort(InputStream input) throws IOException {
		return (input.read() & 0xFF) | (input.read() & 0xFF) << 8;
	}
	
	public static int fillBuffer(InputStream input, byte[] buff) throws IOException {
		int read = 0;
		while( (read += (read+input.read(buff,read, buff.length-read))) != buff.length );
		assert read == buff.length;
		return read;
	}
	
	public static long readUnsignedInt(byte[] buffer, int i) {
		return (buffer[i+0] & 0xFFl) | (buffer[i+1] & 0xFFl) << 8 | (buffer[i+2] & 0xFFl) << 16 | (buffer[i+3] & 0xFF) << 24;
	}
	
	public static int readSignedInt(byte[] buffer, int i) {
		return (buffer[i+0] & 0xFF) | (buffer[i+1] & 0xFF) << 8 | (buffer[i+2] & 0xFF) << 16 | (buffer[i+3] & 0xFF) << 24;
	}
	
	public static int[] toSignedInts(byte[] buffer){
		int[] r = new int[buffer.length/4];
		for (int i = 0; i < r.length; i++) {
			r[i] = EndianUtils.readSwappedInteger(buffer, i*4);
		}
		return r;
	}
	
	public static ArrayList<Integer> toSignedIntsList(byte[] buffer) {
		
		ArrayList<Integer> l = new ArrayList<Integer>(buffer.length/4);
		
		for (int j = 0; j < buffer.length/4; j++) {
			l.add(IOUtil.readSignedInt(buffer, j*4));
		}
		return l;
	}
	
	
	
}
